package com.cell.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cell.dao.UserDao;
import com.cell.dao.location.CityDao;
import com.cell.dao.location.ProvinceDao;
import com.cell.dao.recyclables.RecyclableNameDao;
import com.cell.dao.recyclables.RecyclableTypeDao;
import com.cell.entity.Order;
import com.cell.entity.User;
import com.cell.service.OrderService;
import com.cell.service.UserService;
import com.cell.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 继承IServiceImpl的基础service接口实现方法
 * 注册信息校验以及密码的加密传送可另建立工具类来实现
 *
 * @author cloudJiang
 * @date 2022/5/11 20:15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserUtil userUtil;
    @Autowired
    private OrderService orderService;

    @Override
    public int login(String loginKey, String password, HttpSession session) throws NoSuchAlgorithmException {
        if (loginKey != null && !loginKey.isEmpty() && password != null && !password.isEmpty()) {
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(User::getLoginKey, loginKey);
            User user = userDao.selectOne(lambdaQueryWrapper);
            if (user != null) {
                if (!user.getPassword().equals(
                        userUtil.encryptByMD5(password.getBytes(StandardCharsets.UTF_8)))) {
                    return 3;
                } else {
                    //记录登陆状态
                    session.setAttribute("user", user);
                    return 0;
                }
            } else {
                return 2;
            }
        } else {
            return 1;
        }
    }

    @Override
    public int signUp(User user) {
        //字段校验
        try {
            userUtil.validateUser(user);
        } catch (Exception e) {
            return 1;
        }
        //检验数据库中是否已经存在该登陆凭证以及昵称
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("login_key", user.getLoginKey()).or().eq("nickName", user.getNickname());
        if (!userDao.selectList(wrapper).isEmpty()) {
            return 2;
        }
        //加密密码
        try {
            user.setPassword(userUtil.encryptByMD5(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        if (this.save(user)) {
            return 0;
        } else {
            return 2;
        }
    }

    @Override
    public int resetPassword(int id, String password) {
        User user = userDao.selectById(id);
        try {
            user.setPassword(userUtil.encryptByMD5(password.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        this.updateById(user);
        return 0;
    }

    @Override
    public int validOldPassword(int id, String password) {
        User user = userDao.selectById(id);
        if (user == null) {
            return 2;
        }
        try {
            password = userUtil.encryptByMD5(password.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (user.getPassword().equals(password)) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public int validEmailCode(int userID, String code) {
        User user = userDao.selectById(userID);
        return user.getValidCode().equals(code) ? 0 : 1;
    }

    @Override
    public void sendEmail(int userID) {
        User user = userDao.selectById(userID);
        //发送邮件并将返回的验证码存储
        user.setValidCode(
                userUtil.sendValidEMail(user.getLoginKey())
        );
        //将更改后的用户实体存储到数据库
        userDao.updateById(user);
    }

    @Override
    public int commitOrder(int salID, double weight, String type, String name) {
        Order order = new Order();
        order.setSalID(salID);
        order.setWeight(weight);

        return orderService.saveOrder(order, type, name);
    }

    @Override
    public int acceptOrder() {
        return 0;
    }

    @Override
    public int overOrder() {
        return 0;
    }

    @Override
    public int commitErrorOrder() {
        return 0;
    }

    @Override
    public int endOrder() {
        return 0;
    }

    @Override
    public void getAllOrder(int states) {

    }

    @Override
    public void deleteOrder() {

    }


    @Override
    public List<User> getNearbyCommunityAgent(User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("country", user.getCountry());
        map.put("province", user.getProvince());
        map.put("city", user.getCity());
        map.put("district", user.getDistrict());
        map.put("community", user.getCommunity());
        map.put("states", 1);
        return userDao.selectByMap(map);
    }

    @Override
    public List<User> getNearbyDistrictAgent(User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("country", user.getCountry());
        map.put("province", user.getProvince());
        map.put("city", user.getCity());
        map.put("district", user.getDistrict());
        map.put("states", 2);
        return userDao.selectByMap(map);
    }

    @Override
    public void deleteUser(User user) {
        userDao.deleteById(user.getId());
    }


}
